<template>
  <div class="admin-page">
    <div class="page-header">
      <h1 class="page-title">日志管理</h1>
      <p class="page-subtitle">管理系统中的所有工作日志</p>
    </div>
    
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">日志列表</span>
          <div class="header-actions">
            <el-input v-model="q.keyword" placeholder="按标题搜索" clearable style="width: 220px" />
            <el-date-picker v-model="q.date" type="date" placeholder="按日期" style="margin-left:8px"/>
            <el-button type="primary" @click="onSearch" style="margin-left:8px">查询</el-button>
            <el-button type="success" @click="openCreate" style="margin-left:8px">新增日志</el-button>
          </div>
        </div>
      </template>
  <el-table :data="list" size="small" v-loading="loading" :row-key="row=>row.worklogId">
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column prop="worklogId" label="ID" width="80"/>
        <el-table-column prop="title" label="标题"/>
          <el-table-column label="内容">
            <template #default="{ row }">{{ filterSensitiveWords(row.content || '') }}</template>
          </el-table-column>
        <el-table-column prop="logDate" label="日期" width="130"/>
        <el-table-column label="创建者" width="100">
          <template #default="{ row }">
            {{ getUserName(row.creatorId) }}
          </template>
        </el-table-column>
        <el-table-column prop="relatedScheduleId" label="关联日程" width="120"/>
        <el-table-column prop="relatedTeamId" label="所属团队" width="120"/>
        <el-table-column prop="createTime" label="创建时间" width="180">
           <template #default="{ row }">
             {{ formatDateTime(row.createTime) }}
           </template>
         </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/worklogs/${row.worklogId}`)">详情</el-button>
            <el-popconfirm title="确认删除该日志吗？" @confirm="remove(row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:12px; display:flex; justify-content:flex-end">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10,20,50,100]"
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </el-card>
  </div>

  <el-drawer v-model="drawer.visible" :title="drawer.title" size="40%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题"><el-input v-model="form.title"/></el-form-item>
        <el-form-item label="内容"><el-input v-model="form.content" type="textarea" rows="5"/></el-form-item>
        <el-form-item label="日期"><el-date-picker v-model="form.logDate" type="date"/></el-form-item>
        <el-form-item label="关联日程"><el-input v-model.number="form.relatedScheduleId"/></el-form-item>
        <el-form-item label="所属团队"><el-input v-model.number="form.relatedTeamId"/></el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align:right">
          <el-button @click="drawer.visible=false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </div>
      </template>
    </el-drawer>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { api } from '@/utils/api'
import { ElMessage } from 'element-plus'
import { filterSensitiveWords } from '@/utils/sensitive'

const list = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const q = reactive({ keyword: '', date: null })
const drawer = reactive({ visible: false, title: '' })
const form = reactive({ worklogId: null, title: '', content: '', logDate: '', relatedScheduleId: null, relatedTeamId: null })

// 用户映射
const userMap = ref(new Map())

// 获取用户信息
async function loadUserInfo(userIds) {
  if (!userIds || userIds.length === 0) return
  
  try {
    // 过滤掉已经获取过的用户ID
    const newUserIds = userIds.filter(id => !userMap.value.has(id))
    if (newUserIds.length === 0) return
    
    // 批量获取用户信息 - 使用分页方式获取所有用户然后过滤
  const usersResp = await api.get('/user/list', { page: 1, size: 1000 })
  const allUsers = Array.isArray(usersResp) ? usersResp : (usersResp.records || [])
    // 过滤出需要的用户
    const userList = allUsers.filter(user => newUserIds.includes(user.userId))
    
    // 更新用户映射
    userList.forEach(user => {
      if (user.userId) {
        userMap.value.set(user.userId, {
          username: user.username,
          nickname: user.nickname
        })
      }
    })
  } catch (e) {
    console.warn('获取用户信息失败:', e)
  }
}

// 根据用户ID获取用户名
function getUserName(creatorId) {
  if (!creatorId) return '-'
  const user = userMap.value.get(creatorId)
  return user ? (user.username || user.nickname || creatorId) : creatorId
}

// 格式化时间显示
function formatDateTime(dateTime) {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  if (isNaN(date.getTime())) return dateTime
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

async function load() {
  loading.value = true
  try {
    const params = { page: currentPage.value, size: pageSize.value }
    // 管理员可以查看所有用户的工作日志，普通用户只能查看自己的
    const role = sessionStorage.getItem('role')
    const userId = localStorage.getItem('userId')
    
    console.log('=== 工作日志查询调试信息 ===')
    console.log('当前用户角色:', role)
    console.log('当前用户ID:', userId)
    
    if (role !== 'admin') {
      if (userId) params.creatorId = userId
    }
    
    // 预留：将关键词和日期传给后端，当前端口可能忽略
    if (q.keyword) params.keyword = q.keyword
    if (q.date) {
      const ymd = new Date(q.date).toISOString().slice(0, 10)
      params.date = ymd
    }
    
    console.log('API请求参数:', params)
    const data = await api.get('/worklog/list', params)
    console.log('API响应数据:', data)
    if (Array.isArray(data)) {
      // 兼容旧返回：无分页时返回数组
      list.value = data
      total.value = data.length
      console.log('使用数组格式，数据条数:', data.length)
    } else {
      list.value = data?.records || []
      total.value = Number(data?.total || 0)
      console.log('使用分页格式，records条数:', (data?.records || []).length, '总数:', data?.total)
    }
    
    // 获取所有创建者ID并加载用户信息
    const creatorIds = [...new Set(list.value.map(item => item.creatorId).filter(id => id))]
    if (creatorIds.length > 0) {
      await loadUserInfo(creatorIds)
    }
    
    console.log('最终显示的工作日志列表:', list.value)
    console.log('列表中的创建者ID:', list.value.map(item => ({ id: item.worklogId, creatorId: item.creatorId, title: item.title })))
    console.log('=== 调试信息结束 ===')
  } catch (e) {
    ElMessage.error('加载失败：' + (e.message||''))
  } finally {
    loading.value = false
  }
}

function onPageChange(p) {
  currentPage.value = p
  load()
}

function onSizeChange(s) {
  pageSize.value = s
  currentPage.value = 1
  load()
}

function onSearch() {
  currentPage.value = 1
  load()
}

function openCreate() {
  Object.assign(form, { worklogId: null, title: '', content: '', logDate: '', relatedScheduleId: null, relatedTeamId: null })
  drawer.title = '新增日志'
  drawer.visible = true
}

function openEdit(row) {
  Object.assign(form, row)
  drawer.title = '编辑日志'
  drawer.visible = true
}

async function submit() {
  try {
    const payload = { ...form, creatorId: Number(localStorage.getItem('userId')||'0') }
    
    // 处理日期格式：确保logDate是YYYY-MM-DD格式的字符串
    if (payload.logDate) {
      if (payload.logDate instanceof Date) {
        payload.logDate = payload.logDate.toISOString().slice(0, 10)
      } else if (typeof payload.logDate === 'string' && payload.logDate.includes('T')) {
        payload.logDate = payload.logDate.slice(0, 10)
      }
    }
    
    // 过滤掉null、undefined和空字符串的字段，避免后端外键约束错误
    Object.keys(payload).forEach(key => {
      if (payload[key] === null || payload[key] === undefined || payload[key] === '') {
        delete payload[key]
      }
    })
    
    console.log('提交的数据:', payload) // 调试日志
    
    if (form.worklogId) {
      await api.put('/worklog/update', payload)
      ElMessage.success('更新成功')
    } else {
      const res = await api.post('/worklog/add', payload)
      if (res && res.id) form.worklogId = res.id
      ElMessage.success('创建成功')
    }
    drawer.visible = false
    await load()
  } catch (e) {
    console.error('提交错误:', e) // 调试日志
    ElMessage.error('保存失败：' + (e.message||''))
  }
}

async function remove(row) {
  try {
    await api.del(`/worklog/delete/${row.worklogId}`)
    ElMessage.success('删除成功')
    await load()
  } catch (e) {
    ElMessage.error('删除失败：' + (e.message||''))
  }
}

onMounted(load)
</script>

<style scoped>
.admin-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.content-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}
</style>
